const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/visitorQuery/visitorQuery');
const tenantQuery = require('../../db/tenantQuery/tenantQuery')

//引入时间模块
const sd = require('silly-datetime');

//解析token
const {
    token_verify
} = require('../../config/jwt')

//引入scoket通知
const {
    sendSystemMessage_visitor,
    sendSystemMessage_visitor_houseHold
} = require('../../notice/auditNotice')

//申请访客登记
router.post('/apply', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId,
        openId
    } = token_verify(token); //申请者ID,openID
    const houseId = req.body.houseId;
    const visitorName = req.body.visitorName;
    const visitorTel = req.body.visitorTel;
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    pool.query(query.insert_visitor, [userId, houseId, visitorName, visitorTel, time], (error, result) => {
        if (error) {
            res.json(Response.error("申请访客登记失败", null));
            logger().error("申请访客登记失败: " + error);
        } else {
            const visitorId = result.insertId;
            pool.query(tenantQuery.select_houseOwner_id, houseId, (error, result) => {
                if (error) {
                    res.json(Response.error("申请访客登记失败", null));
                    logger().error("申请访客登记失败: " + error);
                    return;
                } else {
                    const user_id = JSON.parse(JSON.stringify(result[0].user_id));
                    sendSystemMessage_visitor(user_id, {
                        openId,
                        applicant: visitorName,
                        message: "您有一则访客申请需处理",
                        time,
                        visitorId
                    });
                    res.json(Response.success("申请访客登记成功", null));
                }
            });
        }
    });
});

//撤销访客申请
router.post('/revoke', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //查询者ID
    const visitorId = req.body.visitorId;
    pool.query(query.revoke_visitor, [userId, visitorId], (error, result) => {
        if (error) {
            res.json(Response.error("撤销我的门禁申请记录失败", null));
            logger().error("撤销我的门禁申请记录失败: " + error);
        } else {
            res.json(Response.success("撤销我的门禁申请记录成功", null));
        }
    });
})

//获取个人的门禁申请记录
router.get('/myDetailed', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //查询者ID
    pool.query(query.select_visitorByuser, userId, (error, result) => {
        if (error) {
            res.json(Response.error("获取我的门禁申请记录失败", null));
            logger().error("获取我的门禁申请记录失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取我的门禁申请记录成功", data));
        }
    });
})

// 房东获取我的访客列表
router.get('/myHouseVisitor', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //查询者ID
    pool.query(query.select_myHouseVisitor, userId, (error, result) => {
        if (error) {
            res.json(Response.error("获取我名下房屋访客记录失败", null));
            logger().error("获取我名下房屋访客记录失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取我名下房屋访客记录成功", data));
        }
    });
})

//房东获取门禁申请记录
router.get('/detailed', function (req, res) {
    const visitorId = req.body.visitorId;
    pool.query(query.select_visitor, visitorId, (error, result) => {
        if (error) {
            res.json(Response.error("获取门禁申请记录失败", null));
            logger().error("获取门禁申请记录失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取门禁申请记录成功", data));
        }
    });
})

//房东修改门禁申请记录
router.post('/changeStatus', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId,
        openId,
        nickName
    } = token_verify(token);
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    const visitorId = req.body.visitorId;
    const visitorStatus = req.body.visitorStatus;
    pool.query(query.select_houseOwn, visitorId, (error, result) => {
        if (error) {
            res.json(Response.error("修改门禁申请记录失败", null));
            logger().error("修改门禁申请记录失败: " + error);
        } else {
            const user_id = JSON.parse(JSON.stringify(result[0].user_id));
            if (user_id != userId) {
                res.json(Response.error("修改门禁申请记录失败", null));
            } else {
                pool.query(query.change_visitor_houseOwner, [visitorStatus, visitorId], (error, result) => {
                    if (error) {
                        res.json(Response.error("修改门禁申请记录失败", null));
                        logger().error("修改门禁申请记录失败: " + error);
                    } else {
                        sendSystemMessage_visitor_houseHold(user_id, {
                            openId,
                            handler: nickName,
                            message: "访客申请已通过业主处理",
                            visitorStatus,
                            time,
                            visitorId
                        });
                        res.json(Response.success("修改门禁申请记录成功", null));
                    }
                });
            }

        }
    });
})

module.exports = router;